<!-- 手签协议 -->
<template>
  <div id="selfWaterStationPickup">
    <c-title :hide="false" text="取货"></c-title>

    <div class="flex-a-c padding-10 bg-fff margin-12 t-l border-radius-8" style="margin-bottom: 0!important;">
      <img class="wh-40" :src="store_info.thumb" alt="" />
      <div class="f-grow-1 margin-left-10 flex-column flex-j-sb">
        <div class="f-16 f-bold line-clamp-2 color-000000">{{ store_info.store_name }}</div>
      </div>
    </div>

    <van-tabs v-model="activeName" @click="handleClick" sticky :ellipsis="false" offset-top="40" color="var(--themeBaseColor)" line-width="20px" background="transparent">
      <van-tab :title="items.name" v-for="(items, ind) in titleArr" :key="ind">
        <div class="list" v-if="dataList[ind] && !fun.isTextEmpty(dataList[ind].list)">
          <div class="list-child" v-for="(item, index) in dataList[ind].list" :key="index">
            <div class="flex-a-c flex-j-sb">
              <div class="f-12">订单号：{{ item.order_sn }}</div>
              <!-- <div class="f-12 themeColor">{{ item.status_name }}</div> -->
            </div>
            <div class="margin-top-6" v-if="item.goods_facility_info">
              <div class="flex " v-for="(good, index) in item.goods_facility_info" :key="index">
                <img class="wh-80" :src="good.goods_thumb" alt="" />
                <div class="f-grow-1 margin-left-10 flex-column flex-j-sb">
                  <div class="f-15 line-clamp-2 color-000000">{{ good.goods_title }}</div>
                  <div class="f-grow-1"></div>
                  <div class="flex-a-c flex-j-sb f-13">
                    <div class="flex-a-c">规格：{{ good.goods_option_title || '' }}</div>
                    <div class="f-14">x {{ good.goods_total || '1' }}</div>
                  </div>
                  <div class="flex-a-c flex-j-sb margin-top-4">
                    <div class="f-13">柜机：{{good.cabinet_sn}}</div>
                    <div>
                      <van-button @click.stop="publicMessage(good.id,btn,btn.msg,true)" v-for="(btn,bi) in good.button_models" color="var(--themeBaseColor)" :key="bi" type="primary" size="mini" round style="padding: 0 14px;">
                        {{ btn.name }}
                      </van-button>
                    </div>
                  </div>

                </div>
              </div>
            </div>

            <div class="margin-top-6 flex-column flex-j-sb bg-f5f5f5 border-radius-8 padding-10">
              <div class="f-12">姓名：{{ item.nickname }}</div>
              <div class="f-14 margin-top-2">{{ item.address }}</div>
            </div>

            <div class="margin-top-6 flex" style="flex-direction: row-reverse;" v-if="item.button_models && item.button_models.length">
              <van-button @click.stop="publicMessage(item.id,btn,btn.msg)" v-for="(btn,bi) in item.button_models" color="var(--themeBaseColor)" :key="bi" type="primary" size="small" round style="padding: 0 14px;">
                {{ btn.name }}
              </van-button>
            </div>
          </div>
        </div>
        <van-empty v-if="!$store.state.isloadding && fun.isTextEmpty(dataList[ind].list)" description="暂无数据" />
      </van-tab>
    </van-tabs>
    <div style="height: 120px;"></div>

    <div class="fixed-bottom padding-10 flex set-pc-styleLeft" v-if="is_worker && activeName == 0">
      <van-button @click.stop="toUrl('installationSeverHome',{},{status: 4})" type="primary" block round color="var(--themeBaseColor)">
        取货完成，去送货
      </van-button>
    </div>
  </div>
</template>

<script>
import { scrollMixin } from "utils/mixin";
export default {
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      store_info: {},
      is_worker: false,
      keyword: "",
      activeName: 0,
      dataList: [],
      titleArr: [],
      isLoadMore: true,

      loading: false
    };
  },

  activated() {
    this.store_id = this.$route.query.sid;
    this.device_id = this.$route.query.did;
    this.init();
  },
  created() {
    this.activeName = Number(this.$route.query.sta) || 0;
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    toUrl(name, params = {}, query = {}) {
      this.$router.push(this.fun.getUrl(name, params, query));
    },
    init() {
      this.dataList = [];
      this.titleArr = [
        { id: 0, name: "待取货", url: 'plugin.self-water-station.frontend.take-delivery.self-delivery' },
        { id: 1, name: "待还桶", url: 'plugin.self-water-station.frontend.take-delivery.self-delivery' },
      ];
      this.isLoadMore = true;
      this.setNewArr();
    },
    setNewArr() {
      this.titleArr.forEach((val, index) => {
        this.dataList.push({
          isLoadMore: true,
          loading: false,
          finished: false,
          page: 1,
          total_page: 0,
          list: [],
          url: val.url,
        });
      });
      this.handleClick();
    },
    onLoad() {},
    onSearch() {
      this.dataList[this.activeName].list = [];
      this.dataList[this.activeName].page = 1;
      this.handleClick();
    },
    handleClick() {
      // if (!this.fun.isTextEmpty(this.dataList[this.activeName].list)) {
      //   this.isLoadMore = this.dataList[this.activeName].isLoadMore;
      //   return;
      // }
      let _url = this.dataList[this.activeName].url;
      $http
        .get(_url, { page: 1, store_id: this.store_id, device_id: this.device_id, return_bucket: this.activeName }, ".")
        .then(response => {
          if (response.result === 1) {
            this.is_worker = response.data.is_worker;
            if(!response.data.is_worker) {
              this.titleArr.splice(1, 1); //不是安装师傅，删除待还桶
            }
            this.store_info = response.data.store_info;
            this.isLoadMore = true;
            this.dataList[this.activeName].isLoadMore = true;
            this.dataList[this.activeName].page = 1;
            this.dataList[this.activeName].total_page = response.data.list.last_page;
            this.$set(this.dataList[this.activeName], "list", response.data.list.data);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    //获取更多数据
    getMoreData() {
      const that = this;
      that.dataList[that.activeName].isLoadMore = false;
      that.isLoadMore = false; // 防止多次请求分页数据
      if (that.dataList[that.activeName].page >= that.dataList[that.activeName].total_page) {
        return;
      } else {
        let _json = {
          // "search[title]": this.keyword,
          // status: this.activeName
          store_id: this.store_id,
          device_id: this.device_id,
          return_bucket: this.activeName
        };
        that.dataList[that.activeName].page = that.dataList[that.activeName].page + 1;
        _json.page = that.dataList[that.activeName].page;
        let _url = this.dataList[this.activeName].url;
        $http.get(_url, _json, "加载中").then(
          response => {
            that.isLoadMore = true;
            that.dataList[that.activeName].isLoadMore = true;
            if (response.result === 1) {
              var myData = response.data.list.data;
              that.dataList[that.activeName].list = that.dataList[that.activeName].list.concat(myData); //数组拼接
            } else {
              that.dataList[that.activeName].page = that.dataList[that.activeName].page - 1;
              that.dataList[that.activeName].isLoadMore = false;
              that.isLoadMore = false;
            }
          },
          function(response) {
            // error callback
          }
        );
      }
    },
    async queryCabinetStatus(id) {

      let { result, msg, data } = await $http.get(
        "plugin.self-water-station.frontend.take-delivery.get-single-take-status",
        {
          id : id,
          return_bucket: this.activeName
        },
      );
      if (result == 0) return this.$toast(msg);
      // 如果柜机状态为取货中，则轮询查询柜机状态，沦陷次数不超过30次
      if (data && data.status == 0) {
        setTimeout(() => {
          this.queryCabinetStatusNumber += 1;
          if (this.queryCabinetStatusNumber > 15) {
            this.$dialog.alert({
              title: '失败',
              message: '取货超时。请稍后重试或联系客服',
            }).then(() => {
              this.onSearch();
            });
            return;
          }
          this.queryCabinetStatus(id);
        }, 1500);
      } else {
        if(this.qhToast) {
          this.qhToast.clear();
        }
        this.$dialog.alert({
          message: msg,
        }).then(() => {
          this.onSearch();
        });
      }
    },

    publicMessage(id, btn, text,loop) {
      let _text = text ? text : '确定' + btn.name + '?';
      if (!btn.api) {
        return;
      }
      this.$dialog
        .confirm({ message: `${_text}` })
        .then(() => {
          let json = {
            id: id,
            return_bucket: this.activeName
          };
          let urls = btn.api || "";
          $http.get(urls, json).then(
            (response)=> {

              if (response.result == 1) {
                if (loop) {
                  //loop为true时，表示是取货操作，需要轮询查询柜机状态
                  this.qhToast = this.$toast.loading({
                    message: '正在取货中，请稍后...',
                    forbidClick: true,
                    duration: 0 // 设置为0表示不自动关闭
                  });
                  this.queryCabinetStatusNumber = 0;//轮询次数
                  this.queryCabinetStatus(id);
                  return;
                }
                this.$dialog.alert({ message: response.msg });
                this.onSearch();
              } else {
                this.$dialog.alert({ message: response.msg });
              }
            },
            function(response) {
              console.log(response);
            }
          );
        })
        .catch(() => {});
    },
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
#selfWaterStationPickup {
  .wh-40 {
    width: 2.5rem;
    height: 2.5rem;
    display: block;
    border-radius: 0.5rem;
  }
  ::v-deep .van-sticky--fixed {
    background: #fff;
  }
  .list {
    padding: 0.875rem;

    .list-child {
      text-align: left;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      border-radius: 0.5rem;
      overflow: hidden;
      margin-bottom: 0.75rem;
      padding: 0.875rem;
    }
    .wh-80 {
      width: 5rem;
      height: 5rem;
      display: block;
      border-radius: 0.5rem;
    }
  }
}
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 100;
  box-shadow: 0px 0 5px 1px #f5f5f5;
}
</style>
